package controller

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"gormstu/model"
	"net/http"
)

type MultiToMultiController struct {
}

// SearchStudentAndLesson 查询学生信息并展示对应课程
func (mtm MultiToMultiController) SearchStudentAndLesson(ctx *gin.Context) {
	var StudentAndLesson []model.Student
	model.DB.Preload("Lesson").Find(&StudentAndLesson)
	ctx.JSON(http.StatusOK, gin.H{
		"msg": StudentAndLesson,
	})

}

// 查询某个学生的课程

func (mtm MultiToMultiController) SearchSingleStudentLesson(ctx *gin.Context) {
	var SingleStudent model.Student
	model.DB.Preload("Lesson").Where("name = ?", "张三").Find(&SingleStudent)
	ctx.JSON(http.StatusOK, gin.H{
		"msg": SingleStudent,
	})

}

// SearchLessonStudent 查询课程被哪些学生选修了
func (mtm MultiToMultiController) SearchLessonStudent(ctx *gin.Context) {
	var LessonStudent []model.Lesson
	model.DB.Preload("Student").Find(&LessonStudent)
	ctx.JSON(http.StatusOK, gin.H{
		"msg": LessonStudent,
	})

}

// SearchGolangStudent 查询Golang被哪些学生选修了
func (mtm MultiToMultiController) SearchGolangStudent(ctx *gin.Context) {
	var GolangStudent []model.Lesson
	model.DB.Preload("Student").Where("name = ?", "Golang").Find(&GolangStudent)
	ctx.JSON(http.StatusOK, gin.H{
		"msg": GolangStudent,
	})

}

// SearchCondition 指定条件查询数据 ==> 其他条件用法相同 不再赘述
func (mtm MultiToMultiController) SearchCondition(ctx *gin.Context) {
	var GolangStudent []model.Lesson
	model.DB.Preload("Student").Limit(2).Find(&GolangStudent)
	ctx.JSON(http.StatusOK, gin.H{
		"msg": GolangStudent,
	})
}

// SearchLessonStudentRemoveStudent 张三被开除, 查询课程被选修的时候去掉张三
func (mtm MultiToMultiController) SearchLessonStudentRemoveStudent(ctx *gin.Context) {
	var RemoveStudent []model.Lesson
	model.DB.Preload("Student", "id != ?", 1).Find(&RemoveStudent)
	ctx.JSON(http.StatusOK, gin.H{
		"msg": RemoveStudent,
	})
}

// SearchLessonOrderDesc 预加载sql, 查看课程被哪些学生选修了, 倒序 id 输出
func (mtm MultiToMultiController) SearchLessonOrderDesc(ctx *gin.Context) {
	var orderLesson []model.Lesson
	model.DB.Preload("Student", func(db *gorm.DB) *gorm.DB {
		return model.DB.Order("student.id Desc")
	}).Find(&orderLesson)
	ctx.JSON(http.StatusOK, gin.H{
		"msg": orderLesson,
	})
}
